<?php

class Document_User extends Mongo_Document
{

    protected $_name = 'users';

    public function getTitle()
    {
        return $this -> name;
    }

    public function __toString()
    {
        return $this -> name;
    }

    /**
     * set password
     * @param string $string
     * @return Document_User
     *
     */
    public function setPassword($string)
    {
        $this -> salt = Text::random(8);
        $this -> password = $this -> _createPassword($string, $this -> salt);
        return $this;
    }

    /**
     * @return bool
     * is valid password
     */
    public function isPassword($string)
    {
        return $this -> _createPassword($string, $this -> salt) == $this -> password;

    }

    protected function _createPassword($string, $salt)
    {
        return sha1($string . $salt, false);
    }

    public function login()
    {
        $this -> login_ip = Request::initiator() -> getClientIp();
        $this -> login_at = time();
        $this -> save();

        // setup cookie
        $_SESSION['uid'] = $this -> _id;
    }

}
